package com.ruoyi.fly.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.fly.domain.*;
import com.ruoyi.fly.domain.vo.*;
import com.ruoyi.fly.enums.DeliveryMethodType;
import com.ruoyi.fly.enums.ProductType;
import com.ruoyi.fly.mapper.*;
import com.ruoyi.fly.service.AppletProductOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

@Service
public class AppletProductOrderServiceImpl implements AppletProductOrderService {

    @Autowired
    private AppletProductOrderMapper appletProductOrderMapper;

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private VehiclesMapper vehiclesMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CeresMemberAddressMapper ceresMemberAddressMapper;

    @Autowired
    private AgentUserMapper agentUserMapper;

    @Autowired
    private AgentStoreCarMapper agentStoreCarMapper;


    /**
     * 根据id查询订单
     *
     * @param id
     * @return
     */
    @Override
    public ProductOrderVo selectAppletProductOrderById(String id) {
        ProductOrderVo productOrderVo = new ProductOrderVo();
        AppletProductOrder appletProductOrder = appletProductOrderMapper.selectAppletProductOrderById(id);
        Store store = storeMapper.selectStoreById(appletProductOrder.getStoreId());
        Vehicles vehicles = vehiclesMapper.selectPcVehiclesById(appletProductOrder.getVehiclesId());
        Product product = productMapper.selectProductById(appletProductOrder.getProductId());
        BeanUtils.copyProperties(appletProductOrder, productOrderVo);
        productOrderVo.setProductName(product.getProductName());
        productOrderVo.setStoreName(store.getStoreName());
        productOrderVo.setLicensePlate(vehicles.getLicensePlate());
        return productOrderVo;
    }

//    @Override
//    public OrderIncomeVo getOrderIncome(OrderVo orderVo) {
//        OrderIncomeVo orderIncomeVo = new OrderIncomeVo();
//        BigDecimal grossIncome = incomeMapper.selectGrossIncome(orderVo);
//        BigDecimal todayIncome = incomeMapper.selectTodayIncome();
//        List<Map<String, Object>> storeIncome = incomeMapper.selectStoreIncome(orderVo);
//        List<Map<String, Object>> licenseIncome = incomeMapper.selectStoreIncome(orderVo);
//        orderIncomeVo.setTotalIncome(grossIncome);
//        orderIncomeVo.setTodayIncome(todayIncome);
//        orderIncomeVo.setStoreIncome(storeIncome);
//        orderIncomeVo.setVehicleIncome(licenseIncome);
//        return orderIncomeVo;
//    }

//    @Override
//    public OrderIncomeVo getOrderIncome() {
//        OrderIncomeVo orderIncomeVo = new OrderIncomeVo();
//        //获取总收入
//        BigDecimal totalIncome = appletProductOrderMapper.getOrderIncome(null, null, null);
//        orderIncomeVo.setTotalIncome(totalIncome);
//        //获取当日收入
//        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT);
//        LocalDateTime todayEnd = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
//        BigDecimal orderIncome = appletProductOrderMapper.getOrderIncome(todayStart.toString(), todayEnd.toString(), null);
//        orderIncomeVo.setTodayIncome(orderIncome);
//        //获取门店收入
//        BigDecimal orderIncome1 = appletProductOrderMapper.getOrderIncome(null, null, 2);
//        orderIncomeVo.setStoreIncome(orderIncome1);
//        //获取车辆收入
//        BigDecimal orderIncome2 = appletProductOrderMapper.getOrderIncome(null, null, 1);
//        orderIncomeVo.setVehicleIncome(orderIncome2);
//        return orderIncomeVo;
//    }

    @Override
    public OrderIncomeVo getOrderIncome(OrderVo orderVo) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        AgentUser agentUser = agentUserMapper.selectSysUserByUserId(userId.toString());
        if (Objects.equals(agentUser.getAgentType(), "1")) {
            OrderIncomeVo orderIncomeVo = new OrderIncomeVo();
            //获取总收入
            BigDecimal totalIncome = appletProductOrderMapper.selectOrderSum(orderVo);
            if (StringUtils.isEmpty(orderVo.getStartTime()) && StringUtils.isEmpty(orderVo.getEndTime())) {
                //获取当日收入
                BigDecimal todayIncome = appletProductOrderMapper.selectByTodayIncome();
                if (todayIncome == null) {
                    todayIncome = BigDecimal.ZERO;
                }
                orderIncomeVo.setTodayIncome(todayIncome);
            } else {
                //获取当日收入
                List<Map<String, Object>> maps = appletProductOrderMapper.selectTodayIncome(orderVo);
                if (maps.size() == 1) {
                    BigDecimal todayIncome = (BigDecimal) maps.get(0).get("today_income");
                    orderIncomeVo.setTodayIncome(todayIncome);
                } else {
                    orderIncomeVo.setTodayIncome(BigDecimal.ZERO);
                }

            }
            //门店总收入
            List<Map<String, Object>> storeIncome = appletProductOrderMapper.selectStoreIncome(orderVo);
            if(storeIncome.size()==0){
                List<Map<String, Object>> ma = appletProductOrderMapper.selectTodayIncome(new OrderVo());
                if (ma.size()>0){
                    for(int i=0;i<ma.size();i++){
                        ma.get(i).put("store_income",0.0);
                    }
                    orderIncomeVo.setStoreTodayIncome(ma);
                }
            }else {
                orderIncomeVo.setStoreTodayIncome(storeIncome);
            }

            BigDecimal storeGrossIncome = BigDecimal.ZERO;
            for (Map<String, Object> map : storeIncome) {
                BigDecimal income = (BigDecimal) map.get("store_income");
                if (income != null) {
                    storeGrossIncome = storeGrossIncome.add(income);
                }
            }
            //车辆总收入
            List<Map<String, Object>> licenseIncome = appletProductOrderMapper.selectLicenseIncome(orderVo);
            orderIncomeVo.setLicenseTodayIncome(licenseIncome);
            BigDecimal licenseGrossIncome = BigDecimal.ZERO;
            for (Map<String, Object> map : licenseIncome) {
                BigDecimal income = (BigDecimal) map.get("liccense_income");
                if (income != null) {
                    licenseGrossIncome = licenseGrossIncome.add(income);
                }
            }
            orderIncomeVo.setTotalIncome(totalIncome);
            orderIncomeVo.setStoreIncome(storeGrossIncome);
            orderIncomeVo.setVehicleIncome(licenseGrossIncome);
            return orderIncomeVo;
        } else if (Objects.equals(agentUser.getAgentType(), "2")) {
            OrderIncomeVo orderIncomeVo = new OrderIncomeVo();
            List<AgentStoreCar> agentStoreCars = agentStoreCarMapper.selectAgentStoreCarByUserId(agentUser.getUserId());
            for(AgentStoreCar agentStoreCar : agentStoreCars){
                //每个门店收入
                List<Map<String, Object>> storeTodayIncome = appletProductOrderMapper.selectStoreTodayIncome(agentStoreCar.getStoreId(), orderVo);
                if(storeTodayIncome.size()==0){
                    List<Map<String, Object>> storeTodayIncomes = appletProductOrderMapper.selectStoreTodayIncome(agentStoreCar.getStoreId(), new OrderVo());
                    for(int i=0;i<storeTodayIncomes.size();i++){
                        storeTodayIncomes.get(i).put("store_income",0.0);
                    }
                    orderIncomeVo.setStoreTodayIncome(storeTodayIncomes);
                }else {
                    orderIncomeVo.setStoreTodayIncome(storeTodayIncome);
                }
                //门店总收入
                BigDecimal storeGrossIncome = BigDecimal.ZERO;
                for (Map<String, Object> map : storeTodayIncome) {
                    BigDecimal income = (BigDecimal) map.get("store_income");
                    if (income != null) {
                        storeGrossIncome = storeGrossIncome.add(income);
                    }
                }
                //今日收入
                if ((orderVo.getStartTime() == null && orderVo.getEndTime() == null)) {
                    BigDecimal agentStoreTodayIncome = appletProductOrderMapper.selectAgentStoreByTodayIncome(agentStoreCar.getStoreId());
                    BigDecimal agentLicenseTodayIncome = appletProductOrderMapper.selectAgentLicenseByTodayIncome(agentStoreCar.getCarId());
                    agentStoreTodayIncome = agentStoreTodayIncome.add(agentLicenseTodayIncome);
                    orderIncomeVo.setTodayIncome(agentStoreTodayIncome);
                } else {
                    List<Map<String, Object>> maps = appletProductOrderMapper.selectAgentStoreTodayIncome(agentStoreCar.getStoreId(), orderVo);
                    List<Map<String, Object>> maps1 = appletProductOrderMapper.selectAgentLicenseTodayIncome(agentStoreCar.getCarId(), orderVo);
                    BigDecimal todayIncome = BigDecimal.ZERO;
                    if (maps.size() == 1) {
                        BigDecimal agentStoreTodayIncome = (BigDecimal) maps.get(0).get("today_income");
                        //  orderIncomeVo.setTodayIncome(agentStoreTodayIncome);
                        todayIncome = agentStoreTodayIncome;
                    }
                    if (maps1.size() == 1) {
                        BigDecimal agentLicenseTodayIncome = (BigDecimal) maps1.get(0).get("today_income");
                        todayIncome = todayIncome.add(agentLicenseTodayIncome);
                        orderIncomeVo.setTodayIncome(todayIncome);
                    }
                    else {
                        orderIncomeVo.setTodayIncome(BigDecimal.ZERO);
                    }
                }
                //每个车辆收入
                List<Map<String, Object>> licenseTodayIncome = appletProductOrderMapper.selectLicenseTodayIncome(agentStoreCar.getCarId(), orderVo);
                orderIncomeVo.setLicenseTodayIncome(licenseTodayIncome);
                //车辆总收入
                BigDecimal licenseGrossIncome = BigDecimal.ZERO;
                for (Map<String, Object> map : licenseTodayIncome) {
                    BigDecimal income = (BigDecimal) map.get("liccense_income");
                    if (income != null) {
                        licenseGrossIncome = licenseGrossIncome.add(income);
                    }
                }
                BigDecimal totalIncome = licenseGrossIncome.add(storeGrossIncome);
                orderIncomeVo.setStoreIncome(storeGrossIncome);
                orderIncomeVo.setVehicleIncome(licenseGrossIncome);
                orderIncomeVo.setTotalIncome(totalIncome);
            }
/*            agentStoreCars.forEach(agentStoreCar -> {

            });*/
            return orderIncomeVo;
        }

        return null;
    }

    /**
     * 查询产品/服务订单列表
     *
     * @param allOrderVo
     * @return
     */
    @Override
    public R selectAppletProductServerOrderList(AllOrderVo allOrderVo) {
        PageHelper.startPage(allOrderVo.getPageNum(), allOrderVo.getPageSize());
        List<AllOrder> orderVos = appletProductOrderMapper.selectAppletProductServerOrderList(allOrderVo);
        PageInfo<AllOrder> pageInfo = new PageInfo<>(orderVos);
        return R.ok(pageInfo);
    }

//    @Override
//    public List<OrderVo> selectAppletProductServerOrderList(AppletOrderSearchVo appletProductOrder) {
//
//        List<OrderVo> orderVos = appletProductOrderMapper.selectAppletProductServerOrderList(appletProductOrder);
//        if(orderVos!=null){
//            for (OrderVo orderVo : orderVos) {
//                if(orderVo.getOrderMode()!=null){
//                if(orderVo.getOrderType()==0&&orderVo.getOrderMode()==0){
//                    //AppletProductOrder appletProductOrder1 = appletProductOrderMapper.selectAppletProductOrderById(orderVo.getOrderId().toString());
//                    //orderVo.setExpressNo(appletProductOrder1.getExpressNo());
//                }
//                }
//            }
//        }
//        if(appletProductOrder.getProductStatus()!=null&&appletProductOrder.getServiceStatus()==null){
//            List<OrderVo> filteredOrderVos = orderVos.stream()
//                    .filter(orderVo -> orderVo.getOrderType() == 0)
//                    .collect(Collectors.toList());
//            return filteredOrderVos;
//        }
//        if(appletProductOrder.getProductStatus()==null&&appletProductOrder.getServiceStatus()!=null){
//            List<OrderVo> filteredOrderVos = orderVos.stream()
//                    .filter(orderVo -> orderVo.getOrderType() == 1)
//                    .collect(Collectors.toList());
//            return filteredOrderVos;
//        }
//
//
//        return orderVos;
//    }

    /**
     * 查询订单列表
     *
     * @param appletProductOrder
     * @return
     */
    @Override
    public List<ProductOrderVo> selectAppletProductOrderList(AppletProductOrderSearchVo appletProductOrder) {
        List<ProductOrderVo> appletProductOrders = appletProductOrderMapper.selectAppletProductOrderList(appletProductOrder);
        appletProductOrders.forEach(appletProductOrder1 -> {
            if (storeMapper.selectStoreById(appletProductOrder1.getStoreId()) != null) {
                appletProductOrder1.setStoreName(storeMapper.selectStoreById(appletProductOrder1.getStoreId()).getStoreName());
            }
            if (vehiclesMapper.selectPcVehiclesById(appletProductOrder1.getVehiclesId()) != null) {
                appletProductOrder1.setLicensePlate(vehiclesMapper.selectPcVehiclesById(appletProductOrder1.getVehiclesId()).getLicensePlate());
            }
            if (productMapper.selectProductById(appletProductOrder1.getProductId()) != null) {
                appletProductOrder1.setProductName(productMapper.selectProductById(appletProductOrder1.getProductId()).getProductName());
            }
            if (ceresMemberAddressMapper.selectByAddressId(appletProductOrder1.getMid()) != null) {
                appletProductOrder1.setUserName(ceresMemberAddressMapper.selectByAddressId(appletProductOrder1.getMid()).getUserName());
            }
            if (ceresMemberAddressMapper.selectByAddressId(appletProductOrder1.getAddressId()) != null) {
                appletProductOrder1.setCity(ceresMemberAddressMapper.selectByAddressId(appletProductOrder1.getAddressId()).getCity());
            }
            if (appletProductOrder1.getProductStatus() != null) {
                appletProductOrder1.setProductStatusName(ProductType.getValue(Integer.parseInt(String.valueOf(appletProductOrder1.getProductStatus()))));
            }
            if (appletProductOrder1.getDeliveryMethod() != null) {
                appletProductOrder1.setDeliveryMethodName(DeliveryMethodType.getValue(Integer.parseInt(String.valueOf(appletProductOrder1.getDeliveryMethod()))));
            }
        });
        return appletProductOrders;
    }

//    /**
//     * 根据条件查询订单
//     * @param productOrderQueryVo
//     * @return
//     */
//    @Override
//    public AppletProductOrder selectAppletProductOrder(ProductOrderQueryVo productOrderQueryVo) {
//        return appletProductOrderMapper.selectAppletProductOrder(productOrderQueryVo);
//    }

    /**
     * 添加快递单号
     *
     * @param appletProductOrderVo
     * @return
     */
    @Override
    public R updateAppletProductOrder(AppletProductOrderVo appletProductOrderVo) {
        AllOrder allOrder = appletProductOrderMapper.selectAllOrderByOrderCode(appletProductOrderVo.getOrderCode());

        if (allOrder == null) {
            return R.fail("订单不存在");
        }
        if (allOrder.getOrderType() == 0){
            if (allOrder.getServiceMethod().equals("快递配送")) {
                appletProductOrderMapper.updateAppletProductOrder(appletProductOrderVo);
                return R.ok("添加成功");
            }else {
                return R.fail("该订单不是快递配送，不能添加快递单号");
            }
        }else {
            return R.fail("该订单不是产品订单，不能添加快递单号");
        }
    }

    /**
     * 删除订单
     *
     * @param id
     * @return
     */
    @Override
    public R deleteAppletProductOrderById(String id) {
        return appletProductOrderMapper.deleteAppletProductOrderById(id) > 0 ? R.ok("删除成功") : R.fail("删除失败");
    }

    /**
     * 批量删除订单
     *
     * @param ids
     * @return
     */
    @Override
    public R deleteAppletProductOrderByIds(String[] ids) {
        return appletProductOrderMapper.deleteAppletProductOrderByIds(ids) > 0 ? R.ok("删除成功") : R.fail("删除失败");
    }
}
